package com.example.fw;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;

public class AccountHelper extends WebDriverHelperBase{

	public AccountHelper(ApplicationManager manager) {
		super(manager);
	}

	public String getConfirmationLink(String text){
		Pattern regexp = Pattern.compile("https\\S*");
		Matcher matcher = regexp.matcher(text);
		
		if (matcher.find())
			return matcher.group();
		else
			return "";
	}

	public void signup(User user) {
		String selector = "/html/body/div[4]/span[1]/a";
		click(By.xpath(selector));

		type(By.name("username"), user.login);
	    type(By.name("email"), user.email);
	    click(By.cssSelector("input.button"));
	    
	    WebElement errorMessage = findElement(By.cssSelector("table.width50 tbody tr td p"));
	    if (errorMessage != null){
	    	throw new RuntimeException(errorMessage.getText());
	    }
	    
	    pause(3000);
	    
	    String msg = manager.getMailHelper().getNewMail(user.login, user.password);
	    String confirmationLink = getConfirmationLink(msg);
	    openAbsoluteUrl(confirmationLink);

	    type(By.name("password"), user.password);
	    type(By.name("password_confirm"), user.password);
	    click(By.cssSelector("input.button"));

	}

	public void login(User user) {
		//openUrl("/");
	    type(By.name("username"), user.login);
	    type(By.name("password"), user.password);

	    click(By.cssSelector("input.button"));
	}

	public String loggedUser(User user) {
		String xpathExpression = "/html/body/table/tbody/tr/td[1]/span[1]";
		
		WebElement element = findElement(By.xpath(xpathExpression ));
		return element.getText();
	}

	public void logout() {
		String xpathExpression = "html/body/table[2]/tbody/tr/td[1]/a[10]";
		click(By.xpath(xpathExpression));
	}

}
